<template>
    <view class="search_contain">
        <Search
            bgColor="#F5F5F5"
            @inputValue="inputValue"
            :contentValue="content"
            :contentColor="props.contentColor"
            :hotKeyword="props.hotKeyword"
            :position="props.position"
            @search="search" />
    </view>
    <!-- 搜索商品列表 -->
    <scroll-view class="custom-scroll" lower-threshold="100" scroll-y="true" @scrolltolower="lowerHandle">
        <view class="search_content" v-if="hotList.length">
            <view class="search_contain" v-for="(item, index) in hotList" :key="index" @click.stop="jump(1, item)">
                <view class="search_img common">
                    <GoodsImgStatus fontSize="22rpx" width="91rpx" lineWidth="69rpx" v-if="item.onSale == 3" />
                    <img
                        class="search_sigle"
                        :src="item.coverSrc || defaultImg"
                        :lazy-load="true"
                        @error="imageError(index)" />
                </view>
                <view class="serch_all">
                    <!-- class="shop-logo" -->
                    <text class="search_name" :class="['search_name', getTagName(item)]">{{ item.goodsName }}</text
                    ><view class="search_row">
                        <view class="hotitem_color">
                            <text class="price-qian">￥</text
                            ><text class="search_money">{{
                                floatDivide(item.goodsMinPrice, 100).toString().indexOf('.') != -1
                                    ? floatDivide(item.goodsMinPrice, 100).toString().split('.')[0]
                                    : floatDivide(item.goodsMinPrice, 100)
                            }}</text
                            ><text
                                class="price-dian"
                                v-if="floatDivide(item.goodsMinPrice, 100).toString().indexOf('.') != -1">
                                {{ '.' + floatDivide(item.goodsMinPrice, 100).toString().split('.')[1] }}</text
                            ><text class="price-qi" v-if="item.goodsMinPrice != item.goodsMaxPrice"> 起 </text>
                        </view>
                        <view class="shop-cart">
                            <view
                                v-if="item.activity?.activity_type == 2"
                                class="seckill_btn"
                                @click.stop="toGoodsDetail(item)">
                                马上抢
                            </view>
                            <image
                                @click.stop="jump(2, item, index)"
                                class="search_icon"
                                v-else-if="item.goodsStock > 0 && item.onSale == 1"
                                :src="getImgOssUrl('/ui-prod-2.0.0/cart_1.1.png')" />
                            <image
                                v-else
                                @click.stop
                                class="search_icon"
                                :src="getImgOssUrl('/ui-prod-2.0.0/icon_img01_disabled.png')"
                                alt="" />
                            <view class="shop-cart-num" v-if="item.cartNum">{{
                                item.cartNum <= 99 ? item.cartNum : '99+'
                            }}</view>
                        </view>
                    </view></view
                >
            </view>
            <view v-if="loadMoreShow" class="loading">
                <text>{{
                    loading.status === 'loading'
                        ? loading.contentText.contentrefresh
                        : loading.contentText.contentnomore
                }}</text>
            </view>
        </view>
    </scroll-view>

    <view class="search_no" v-if="show">
        <img class="no_img" :src="getImgOssUrl('/ui-prod-2.0.0/nodata_1.1.png')" /><text class="no_title"
            >未搜索到相关产品</text
        ><text class="no_title">快去挑挑其他好货吧</text></view
    >
    <!-- 头部搜索栏 -->

    <uni-popup ref="popup" :safe-area="false" @change="change">
        <view class="popup-content">
            <view class="pop_cancel" @click.stop="cancel">
                <img class="pop_logo" :src="getImgOssUrl('/ui-prod-2.0.0/cancel_1.1.png')"
            /></view>
            <skupop
                :goodsId="goodsData.goodsId"
                :goodsNo="goodsData.goodsNo"
                :show="goodsData.show"
                @popup="popup.open('bottom')"
                @close="close"
                @buyGoods="toConfirm"
        /></view>
    </uni-popup>
</template>
<script setup>
import { ref, reactive } from 'vue';
import { onReachBottom, onShow } from '@dcloudio/uni-app';
import Search from '@/components/search';
import skupop from '@/components/skupop';
import router from '@/router';
import request from '@/request';
import { floatDivide, getImgOssUrl, checkToken } from '@/commons/utils.js';
import GoodsImgStatus from '@/components/goodsImgStatus';
import { useTrace } from '@/commons/trace';
const { traceReport } = useTrace({ autoLoad: true });
const defaultImg = ref(getImgOssUrl('/ui-prod-2.0.0/errorImg.png'));

//接受url参数
const props = defineProps({
    contentColor: {
        type: String,
        default: '#fff'
    },
    hotKeyword: {
        type: String,
        default: '商品名称'
    },
    position: {
        type: String,
        default: '1'
    }
});
const goodsData = reactive({ goodsId: '', goodsNo: '', show: false });
const popup = ref();
const content = ref('');
const total = ref(0);
const show = ref(false);
let goodsIndex = ref();
let shopName = ref();
const loading = reactive({
    status: 'loading', // 默认展示上拉显示更多
    contentText: {
        contentrefresh: '加载中…',
        contentnomore: '已经到底啦！'
    }
});
const searchData = reactive({
    goodsName: '',
    shopId: uni.getStorageSync('ZW_SHOP_ID'),
    pageSize: 8,
    pageNum: 1
});

const inputValue = value => {
    content.value = value;
};
const hotList = ref([]);
// 搜索
const search = () => {
    if (!content.value) {
        hotList.value = [];
        show.value = true;
    } else {
        searchData.goodsName = content.value;
        searchData.pageNum = 1;
        loadMoreShow.value = false;
        getgoods('search');
    }
};
const getgoods = param => {
    request('goodslistServ', searchData).then(res => {
        res.data.list.forEach((item, index) => {
            res.data.list[index] = { ...item, cartNum: 0 };
        });
        res.data.list =
            res.data.list?.map(item => {
                item.cartNum = 0;
                if (item.activity?.id && item.activity?.activity_good_type == 2) {
                    let sortArr = item.activity.activity_goods.sort((a, b) => a.spike_price - b.spike_price);
                    item.goodsMinPrice = sortArr[0].spike_price;
                    item.goodsMaxPrice = sortArr[sortArr.length - 1].spike_price;
                }
                return item;
            }) || [];
        hotList.value = param == 'search' ? res.data.list : hotList.value.concat(res.data.list);
        total.value = res.data.totalCount;
        hotList.value.length == total.value ? (loading.status = 'nomore') : (loading.status = 'loading');
        show.value = hotList.value.length ? false : true;
    });
};
const jump = async (index, item, curindex) => {
    if (index == 1) {
        let query = {
            goodsNo: item.goodsNo,
            goodsId: item.goodsId
        };
        if (item.activityId) {
            query.activityId = item.activityId;
        }
        router.push({ path: '/pages-cart/good/index', query });
    } else {
        goodsIndex.value = curindex;
        if (!(await checkToken())) {
            //授权登录
            router.push('/pages-user/login/index');
            return;
        }
        // if (item.skuList.length == 1) {
        //     // sku规格值为1直接购物车+1
        //     const { goodsId } = item;
        //     traceReport('add_cart', {
        //         productId: goodsId,
        //         productName: item.goodsName,
        //         skuId: item.skuList[0].skuId,
        //         skuName: '',
        //         num: 1
        //     });
        //     request('cartAddServ', { skuId: item.skuList[0].skuId, goodsId, quantity: 1 }).then(res => {
        //         uni.showToast({
        //             title: '添加成功！',
        //             icon: 'none'
        //         });
        //         hotList.value[goodsIndex.value].cartNum += 1;
        //     });
        // } else {
        //     //拉起规则悬浮窗;
        //     goodsData.goodsNo = item.goodsNo;
        //     goodsData.goodsId = item.goodsId;
        //     goodsData.show = true;
        // }
        goodsData.goodsNo = item.goodsNo;
        goodsData.goodsId = item.goodsId;
        goodsData.show = true;
    }
};
const change = type => {
    goodsData.show = type.show;
};
const close = param => {
    popup.value.close();
    hotList.value[goodsIndex.value].cartNum += param.quantity;
    goodsData.show = false;
};
const cancel = () => {
    popup.value.close();
    goodsData.show = false;
};
const toConfirm = val => {
    let { quantity, skuId, goodsId } = val;
    router.push({
        path: '/pages-cart/confirm/index',
        query: {
            skuList: JSON.stringify([{ goodsId, quantity, skuId }])
        }
    });
};
const toGoodsDetail = ({ goodsId }) => {
    router.push({
        path: '/pages-cart/good/index',
        query: { goodsId }
    });
};
const getTagName = item => {
    if (item?.activityProgress == 1) {
        return 'manjian_tag';
    }
    if (item.activity?.id && item.activity?.activity_type == 2) {
        return 'miaosha_tag';
    }
    if (item.activity?.id && [3, 4, 5].includes(item.activity?.activity_type)) {
        return 'pintuan_tag';
    }
    return '';
};
const imageError = index => {
    hotList.value[index].coverSrc = defaultImg.value;
};
const loadMoreShow = ref(false);
const lowerHandle = () => {
    loadMoreShow.value = true;
    if (hotList.value.length < total.value) {
        searchData.pageNum = Math.abs(~(hotList.value.length / 8));
        getgoods('reach');
    }
};
</script>
<style lang="scss" scoped src="./index.scss"></style>
